﻿using MediatR;
using Traceability.App.API.Application.Command.Img;
using Traceability.App.Domain.Traceability;
using Traceability.App.ErrorCode;
using Traceability.App.Infrastructrue.Interface;

namespace Traceability.App.API.Application.Handler.Img
{
    public class DelImgHandler : IRequestHandler<DelImgCommand, APIResult<int>>
    {
        private readonly IBaseRepository<ImgInformationModel> imgRepo;

        public DelImgHandler(IBaseRepository<ImgInformationModel> imgRepo)
        {
            this.imgRepo = imgRepo;
        }
        public Task<APIResult<int>> Handle(DelImgCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var res = imgRepo.GetAll().FirstOrDefault(x => x.Batch == request.Batch && x.ImgType == request.ImgType && x.Id == request.Id);
            if (res == null)
            {
                result.Message = "找不到此照片";
                result.Code = APIEnum.Fail;
                return Task.FromResult(result);
            }
            int r = imgRepo.DeleteAsync(res).Result;
            if (r > 0)
            {
                result.Message = "删除照片成功";
                result.Data = r;
                result.Code = APIEnum.Ok;
            }
            else
            {
                result.Message = "删除照片失败";
                result.Data = r;
                result.Code = APIEnum.Fail;
            }
            return Task.FromResult(result);
        }
    }
}
